package com.pipi.fanglan.httpproxy;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.List;

/**
 * Created by pipi on 2017/7/15.
 */
public class LoginProxy {

    public String customGet() throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://httpbin.org/");

            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

                @Override
                public String handleResponse(
                        final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            return responseBody;
        } finally {
            httpclient.close();
        }
    }

    public static String defautGet(String url,CookieStore cookieStore) throws Exception{
        CloseableHttpClient httpclient = null;
        httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
//        Header[] headers = response1.getAllHeaders();
//        printHeader(headers);
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            String stringEntity = EntityUtils.toString(entity1);
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
            return stringEntity;

        } finally {
            response1.close();
        }
    }

    public static String defaultPost(String url, List<NameValuePair> nvps,CookieStore cookieStore) throws Exception{
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);
//        Header[] headers = response2.getAllHeaders();
//        printHeader(headers);
//        System.out.println();
        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String stringEntity = EntityUtils.toString(entity2);
            EntityUtils.consume(entity2);
            return stringEntity;
        } finally {
            response2.close();
        }
    }

    /**
     * 将cookie保存到静态变量中供后续调用
     * @param
     */
    public static CookieStore saveCookieStore(String url) throws Exception {
        System.out.println("----setCookieStore");
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        CookieStore cookieStore = new BasicCookieStore();
        // JSESSIONID
        Header[] headers = response1.getHeaders("Set-Cookie");
        for(Header header : headers){
            String[] valueMaps = header.getValue().replace(" ","").split(";");
            BasicClientCookie cookie = null;
            for(String value : valueMaps){
                String[] keyMaps = value.split("=");
                if("JSESSIONID".equalsIgnoreCase(keyMaps[0])){
                    cookie = new BasicClientCookie(keyMaps[0],keyMaps[1]);
                }
                if(cookie !=null){
                    if("path".equalsIgnoreCase(keyMaps[0])){
                        cookie.setPath(keyMaps[1]);
                    }
                    try {
                        // 获取地址
                        URI uri = new URI(url);
                        String domain = uri.getHost();
                        cookie.setDomain(domain);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            cookieStore.addCookie(cookie);
        }
        return cookieStore;
    }

    private static void printHeader(Header[] headers){
        for(Header header : headers){
            System.out.println(header.getName() + " : " + header.getValue());
        }
    }
}
